package com.bruce.download.core;

import com.bruce.download.constant.Constant;

import java.util.concurrent.atomic.LongAdder;

/**
 * 展示下载信息
 * <br>CreateDate  2021/09/14 16:51:45
 *
 * @author luotuan
 * @version 1.0.0
 */
public class DownloadInfoThread implements Runnable {
    private long httpFileContentLength;

    /**
     * 已下载大小
     */
    public static LongAdder finishedSize = new LongAdder();
    /**
     * 本次累计下载大小
     */
    public static volatile LongAdder downSize = new LongAdder();

    /**
     * 前一次下载大小
     */
    public double preSize;

    private static final String DEFAULT = "Infinity";

    public DownloadInfoThread(long httpFileContentLength) {
        this.httpFileContentLength = httpFileContentLength;
    }

    @Override
    public void run() {
        String fileSize = String.format("%.2f", httpFileContentLength / Constant.MB);
        int speed = (int) ((downSize.doubleValue() - preSize) / 1024d);
        preSize = downSize.doubleValue();
        // 剩余文件大小
        double remainSize = httpFileContentLength - finishedSize.doubleValue() - downSize.doubleValue();
        // 计算剩余时间
        String remainTime = String.format("%.1f", remainSize / 1024d / speed);
        if (DEFAULT.equalsIgnoreCase(remainTime)) {
            remainTime = "-";
        }
        // 已下载大小
        String currentFileSize = String.format("%.2f", (downSize.doubleValue() - finishedSize.doubleValue()) / Constant.MB);
        String downInfo = String.format("已下载 %smb/%smb,速度 %skb/s,剩余时间 %ss",
                currentFileSize, fileSize, speed, remainTime);

        System.out.println();
        System.out.print(downInfo);
    }
}
